﻿using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Furion.CMS.Domain
{
    [SuppressChangedListener]
    public class UserLoginRecord : EntityBase, IEntityTypeBuilder<UserLoginRecord>
    {
        public UserLoginRecord()
        {
            this.LoginTime = DateTimeOffset.UtcNow;
            PostData = new Dictionary<string, object>();
        }

        /// <summary>
        /// 账号
        /// </summary>
        [MaxLength(100), Required]
        public string Account { get; set; }
        /// <summary>
        /// 登录方式
        /// </summary>
        [MaxLength(200)]
        public string Method { get; set; }
        /// <summary>
        /// 主机地址
        /// </summary>
        [MaxLength(100), Required]
        public string Host { get; set; }
        /// <summary>
        /// 来源Url
        /// </summary>
        [MaxLength(200)]
        public string RefererUrl { get; set; }
        /// <summary>
        /// 提交数据
        /// </summary>
        public IDictionary<string, object> PostData { get; set; }
        /// <summary>
        /// 浏览器信息
        /// </summary>
        [MaxLength(800)]
        public string UserAgent { get; set; }
        /// <summary>
        /// 是否登录成功
        /// </summary>
        public bool IsSuccess { get; set; }
        /// <summary>
        /// 登录错误信息
        /// </summary>
        [MaxLength(100)]
        public string ErrorMessage { get; set; }
        /// <summary>
        /// 登录处理的内部异常
        /// </summary>
        public InnerExceptionRecord InnerException { get; set; }
        /// <summary>
        /// 通行证Id,登录成功状态下才记录
        /// </summary>
        public int? PassportId { get; set; }
        /// <summary>
        /// 通行证信息
        /// </summary>
        public virtual UserPassport Passport { get; set; }
        /// <summary>
        /// 登录时间
        /// </summary>
        public DateTimeOffset LoginTime { get; set; }

        public void Configure(EntityTypeBuilder<UserLoginRecord> entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder.UseDefaultTableNameDefine();

            entityBuilder.HasIndex(i => new { i.LoginTime, i.Host, i.Account });

            entityBuilder.Property(p => p.PostData)
                .HasConversion(v => JsonConvert.SerializeObject(v), v => JsonConvert.DeserializeObject<IDictionary<string, object>>(v));

            entityBuilder.HasOne(p => p.Passport)
                .WithMany(p => p.LoginRecords)
                .HasForeignKey(f => f.PassportId)
                .OnDelete(DeleteBehavior.SetNull);

            entityBuilder.OwnsOne(p => p.InnerException);
        }
    }
}
